<?php

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\Controller;
use App\Http\Model\BasicModel;
use App\Http\Model\Manage\ManageLogModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class BasicController extends Controller
{

    protected $viewPath = "manage.default.";

    public function uploadImage(Request $request): array|string
    {
        try{
            $args = $request->all();
            $file= $request->file('file');
            if ($file->isValid()) { //括号里面的是必须加的哦
                //如果括号里面的不加上的话，下面的方法也无法调用的
                //获取文件的扩展名
                $ext = $file->getClientOriginalExtension();
                if (!in_array($ext, ['jpg', 'png', 'gif', 'jpeg']))
                {
                    return errorReturn("上传文件格式错误");
                }
                //获取文件的绝对路径
                $path = $file->getRealPath();
                //定义文件名
                $filename = rand(10000, 99999).time().date('Y-m-d-h-i-s').'.'.$ext;
                // 定义村粗位置
                $savePath = '/manage/upload/'.$args["group"]."/";
                $saveLocalPath = public_path('manage/upload/'.$args["group"]);
                //存储文件。disk里面的manage。总的来说，就是调用disk模块里的manage配置
                Storage::createLocalDriver([
                    'root' => $saveLocalPath,
                    'visibility' => 'public',
                ], $args["group"])->put($filename, file_get_contents($path));
                return successReturn("上传成功",['src'=>$savePath.$filename,'title'=>$filename]);
            }
            else{
                $data = $_FILES['file'];
                $message = match ($data['error']) {
                    1 => "上传的文件超过了 php.ini 中 upload_max_filesize选项限制的值",
                    2 => "上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值",
                    3 => "文件只有部分被上传",
                    4 => "没有文件被上传",
                    6 => "找不到临时文件夹.",
                    7 => "文件写入失败",
                    default => "其他错误，请联想管理员",
                };
                return errorReturn($message);
            }
        }catch (\Exception $e){
            return errorReturn($e->getMessage());
        }
    }

    // 获取验证码
    public function getCaptcha() {
        $captcha = captcha("math");
        return $captcha;
    }

    public function checkCaptcha(string $captcha): bool {
        return captcha_check($captcha);
    }

    public function addLog(string $ltml001, string $ltml002, Request $request, string $ltml003, string $ltml004, string $ltml005, string $ltml006): void {
        $loginInfo = $this->getLoginInfo($request);
        $admin = $loginInfo["admin"];
        $role = $loginInfo["role"];
        $add = array(
            "ltml001"=>$ltml001,
            "ltml002"=>$ltml002,
            "ltml003"=>$ltml003,
            "ltml004"=>$ltml004,
            "ltml005"=>$ltml005,
            "ltml006"=>$ltml006,
            "cLtaCode"=> $admin["code"],
            "uLtarCode"=>$role ? $role["code"] : "CODE",
        );
        (new ManageLogModel)->createInfo($add);
    }

    public function getLoginInfo(Request $request): array
    {
        $admin = $request->session()->get("manage_admin");
        $role = $request->session()->get("manage_role");
        return array(
            "admin"=>$admin,
            "role"=>$role,
        );
    }


    public function checkRoleHasRule(Request $request, string $rule)
    {
        $role = $request->session()->get("manage_role");
        if (!$role) {
            return false;
        }
        $rules = $role["ltarCode"];
    }

    public function getAllAdminUnderCode(string $code, bool $excludeRoot = false): array
    {
        $sql = "WITH RECURSIVE cte AS (
                    -- 初始查询：根节点
                    SELECT code,pCode FROM lt_admin WHERE code = '".$code."'
                    UNION ALL
                    -- 递归部分：子节点
                    SELECT t.code, t.pCode FROM lt_admin t INNER JOIN cte ON t.pCode = cte.code
                ) SELECT * FROM cte";
        $allAdmin = DB::connection("mysql")->select($sql);
        $adminCodes = [];
        foreach ($allAdmin as $admin) {
            if ($excludeRoot && $admin->code == $code) {
                continue;
            }
            $adminCodes[] = $admin->code;
        }
        return $adminCodes;
    }

    public function getAllRoleUnderCode(string $code, bool $excludeRoot = false): array
    {
        $sql = "WITH RECURSIVE cte AS (
                    -- 初始查询：根节点
                    SELECT code,pCode FROM lt_admin_role WHERE code = '".$code."'
                    UNION ALL
                    -- 递归部分：子节点
                    SELECT t.code, t.pCode FROM lt_admin_role t INNER JOIN cte ON t.pCode = cte.code
                ) SELECT * FROM cte";
        $allRole = DB::connection("mysql")->select($sql);
        $roleCodes = [];
        foreach ($allRole as $role) {
            if ($excludeRoot && $role->code == $code) {
                continue;
            }
            $roleCodes[] = $role->code;
        }
        return $roleCodes;
    }

    public function getAllDepartmentUnderCode($code, bool $excludeRoot = false): array
    {
        $sql = "WITH RECURSIVE cte AS (
                    -- 初始查询：根节点
                    SELECT code,pCode FROM lt_admin_department WHERE code = '".$code."'
                    UNION ALL
                    -- 递归部分：子节点
                    SELECT t.code, t.pCode FROM lt_admin_department t INNER JOIN cte ON t.pCode = cte.code
                ) SELECT * FROM cte";
        $allRole = DB::connection("mysql")->select($sql);
        $roleCodes = [];
        foreach ($allRole as $role) {
            if ($excludeRoot && $role->code == $code) {
                continue;
            }
            $roleCodes[] = $role->code;
        }
        return $roleCodes;
    }

    public function getAllNavigationUnderCode($code, bool $excludeRoot = false): array
    {
        $sql = "WITH RECURSIVE cte AS (
                    -- 初始查询：根节点
                    SELECT code,pCode FROM lt_website_navigation WHERE code = '".$code."'
                    UNION ALL
                    -- 递归部分：子节点
                    SELECT t.code, t.pCode FROM lt_website_navigation t INNER JOIN cte ON t.pCode = cte.code
                ) SELECT * FROM cte";
        $allNavigation = DB::connection("mysql")->select($sql);
        $navigationCodes = [];
        foreach ($allNavigation as $role) {
            if ($excludeRoot && $role->code == $code) {
                continue;
            }
            $navigationCodes[] = $role->code;
        }
        return $navigationCodes;
    }


    public function modelStatus(BasicModel $model, string $code, Request $request): array|string
    {
        $has = $model::where([
            ['code', '=', $code],
        ])->first();
        if (!$has)
        {
            return errorReturn("导航不存在");
        }
        $loginInfo = $this->getLoginInfo($request);
        $admin = $loginInfo['admin'];
        $role = $loginInfo['role'];
        $update = (new $model)->updateInfo(dataToWhere([
            "code"=>$code,
            "version"=>$has->version,
        ]), [
            "status"=>$has->status == 1 ? 0: 1,
            "uLtaCode"=>$admin->code,
            "uLtarCode"=>$role->code,
        ]);
        if ($update)
        {
            return successReturn("操作成功");
        }
        return errorReturn("操作失败");
    }

    public function modelDelete(BasicModel $model, string $code, Request $request): array|string
    {
        $has = $model::where([
            ['code', '=', $code],
        ])->first();
        if (!$has)
        {
            return errorReturn("轮播图不存在");
        }
        $loginInfo = $this->getLoginInfo($request);
        $admin = $loginInfo['admin'];
        $role = $loginInfo['role'];
        $delete = (new $model)->deleteInfo([
            ['code', '=', $has->code],
            [ 'version', "=", $has->version],
        ], [
            "uLtaCode"=>$admin->code,
            "uLtarCode"=>$role->code,
        ]);
        if ($delete)
        {
            return successReturn("操作成功");
        }
        return errorReturn("操作失败");
    }
}
